#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/06/10 16:05
# @Author  : elegantfrog
# @FileName: client.py

from utils.config import config
import paho.mqtt.client as mqtt
import paho.mqtt.subscribe as subscribe
import time
import json
import base64
import os
import pymysql
from redis import Redis, ConnectionPool


class aMqtt():
    def __init__(self):
        self.HOST = config['mqtt']['host']
        self.PORT = config['mqtt']['port']
        self.USER = config['mqtt']['username']
        self.PWD = config['mqtt']['password']
        self.KEEPLIVE = 60
        self.client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        self.client = self.client_loop()
        self.sub_topic = 'seedlight/pub/#'
        self.pub_topic = 'seedlight/sub/'
        self.flag = 0

    def connect_redis(self):
        try:
            redis_pool = ConnectionPool(host=config['redis']['host'], port=config['redis']['port'],
                                        password=config['redis']['password'], db=config['redis']['db'],
                                        max_connections=config['redis']['max_connections'])
            redisCli = Redis(connection_pool=redis_pool)
            return redisCli
        except Exception as e:
            print(e)

    def getConnect(self):
        try:
            conn = pymysql.connect(
                host=config['mysql']['host'],
                port=config['mysql']['port'],
                user=config['mysql']['username'],
                password=config['mysql']['password'],
                db=config['mysql']['db'],
            )
            return conn
        except Exception as e:
            print(e)

    def client_loop(self):
        client = mqtt.Client(self.client_id)  # ClientId不能重复，所以使用当前时间
        client.username_pw_set(self.USER, self.PWD)  # 必须设置，否则会返回「Connected with result code 4」
        client.on_connect = self.on_connect
        client.on_message = self.on_message
        client.connect(self.HOST, self.PORT, self.KEEPLIVE)
        client.loop_start()
        return client

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print('mqtt server connection succeeded')
            self.client.subscribe(self.sub_topic)
        else:
            print("Connected with result code " + str(rc))
            print('mqtt server connection failed')

    def on_publish(self, data):
        try:
            self.client.publish(self.pub_topic + data['deviceId'], json.dumps(data['payload']))
        except Exception as e:
            print(e)

    def on_message(self, client, userdata, msg):
        try:
            deviceId = msg.topic.split('/')[-1]
            data = json.loads(msg.payload.decode("utf-8"))
            if data['method'] == 'u1' or data['method'] == 'u0' or data['method'] == 'u2':
                try:
                    redisCli = self.connect_redis()
                    redisCli.hset(deviceId, 'realdata', json.dumps(data['params']))
                    redisCli.connection_pool.disconnect()
                except Exception as e:
                    print(e)
            elif data['method'] == 'u3':
                # redisCli = self.connect_redis()
                # redisCli.hset(deviceId, 'plans', json.dumps(data['params']))
                # redisCli.connection_pool.disconnect()
                pass
            elif data['method'] == 'u5':
                redisCli = self.connect_redis()
                redisCli.hset(deviceId, 'images', json.dumps(data['params']))
                redisCli.connection_pool.disconnect()
            elif data['method'] == 'u10':
                try:
                    redisCli = self.connect_redis()
                    redisCli.hset(deviceId, 'status', data['params']['status'])
                    if data['params']['status'] == 'off':
                        realdata = {
                            "light": 0,
                            "volt": 0,
                            "cur": 0,
                            "brightness": 0,
                            "temp": 0,
                            "tempWarnFlag": 0,
                            "isOpenLight": 0
                        }
                        redisCli.hset(deviceId, 'realdata', json.dumps(realdata))
                    else:
                        conn = self.getConnect()
                        cursor = conn.cursor()
                        querySql = 'select count(1) as total from T_All_Device where deviceId = %s'
                        queryArgs = (deviceId)
                        cursor.execute(querySql, queryArgs)
                        values = cursor.fetchall()
                        if values[0][0] == 0:
                            insetSql = 'insert into T_Device(deviceId, snCode, name) values(%s,%s,%s)'
                            dataItem = {
                                'deviceId': deviceId,
                                'snCode': deviceId,
                                'name': 'LD05'
                            }
                            insertArgs = (dataItem['deviceId'], dataItem['snCode'], dataItem['name'])
                            cursor.execute(insetSql, insertArgs)
                        conn.commit()
                        cursor.close()
                        conn.close()
                    redisCli.connection_pool.disconnect()
                except Exception as e:
                    print(e)

        except Exception as e:
            print(e)


if __name__ == '__main__':
    print(aMqtt().client_loop())
